package com.supermap.wzhy.common.aop;

import com.supermap.wzhy.common.annotation.Role;
import com.supermap.wzhy.common.annotation.RoleContext;
import com.supermap.wzhy.entity.TUsers;
import com.supermap.wzhy.data.MessagePrintUtil;
import com.supermap.wzhy.data.SysConstant;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 *
 * 过滤器，监听向后台请求服务（验证登陆用户有效性）
 *
 * @author Created by TJ on 14-3-7.
 */
public class ReqFilter implements Filter {

    /** 过滤器初始配置对象 */
    private FilterConfig config = null;

    /** 过滤器设置上下文编码 */
    private String encode = "";

    /**
     * 初始化过滤器
     *
     * @param filterConfig
     *            过滤器初始配置对象
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.config = filterConfig;

        // 过滤参数（上下文编码-从web.xml配置中获取）,未设置
        // org.springframework.web.filter.CharacterEncodingFilter代替
        this.encode = this.config.getInitParameter("encoding");
    }

    /**
     * 过滤方法
     *
     * @param request
     *            http请求
     * @param response
     *            http响应
     * @param chain
     *            过滤器链对象
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        // 登录时-不拦截
        if (req.getRequestURI().indexOf("oAuth/login") == -1) {
            chain.doFilter(req, resp);
        } else {
            // 过滤用户后台请求时，HttpSession是否过期
            try {
                HttpSession session = req.getSession();
                TUsers sessionUser = (TUsers) session
                        .getAttribute(SysConstant.CURRENT_USER);
                if (null == sessionUser) {
                    MessagePrintUtil.printMsg("用戶已登录");

                    String uri = req.getRequestURI();
                    // 不拦截登录请求
                    if (uri != null && uri.indexOf("/oAuth") > -1) {
                        try {
                            chain.doFilter(req, resp);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else { // 非登录验证请求

                        // 重定向到判断登录状态，返回登录状态
                        resp.sendRedirect("/data/oAuth/isLogin");
                        return;
                    }

                    return;
                }//end if (null == sessionUser)

                // 获取用户类型Role
                String currentUserName = sessionUser.getUserName();
                Role role = (Role) session.getAttribute(currentUserName);
                // 设置登录用户角色
                RoleContext.INSTANCE.setCurrentRole(role);
            } catch (Exception e) {
                MessagePrintUtil.printException("用户登录失败");
                e.printStackTrace();
                return;
            }

            try {
                //正常执行
                chain.doFilter(req, resp);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 过滤器销毁
     */
    @Override
    public void destroy() {
    }
}
